//
//  JHLCoreEntity.m
//  QPJHDemo
//
//  Created by 7pagame on 2019/2/14.
//  Copyright © 2019年 Vanney. All rights reserved.
//

#import "JHLCoreEntity.h"
#import "SQPJHNetworkManager.h"
#import "QPJHFunDataFormat.h"
#import "QPJHFunRoleModel.h"
#import "QPJFunPayModel.h"
#import "libQPJHLightChannel.h"
#import "QPSaccountStore.h"
#import "UIView+Toast.h"
#import "QPJHUrlHeader.h"
#import "SQPJHTool.h"
#import "YYModel.h"
#import "QPConstHeader.h"
#import "SQPDetectParam.h"
#import "QPJHInitNoticeView.h"
#import "QPJHPayView.h"
#import "QPJHTool.h"
#import "Reachability.h"
#import "QPJHChannelRoleInfo.h"
#import "QPJHChannelOrderInfo.h"

//typedef void (^QPJHSuccessHandle) (id result);

@interface JHLCoreEntity ()<QPJHLightChannelDelegate>

@property (nonatomic, strong) SQPDetectParam *detect;

@property (nonatomic, copy) NSString *platform_id;
@property (nonatomic, copy) NSString *super_user_id;
@property (nonatomic, copy) NSString *roleLevel;
@property (nonatomic, strong) NSDictionary *rolesurperdic;
@property (nonatomic, strong) NSDictionary *loginResponse;

//new add
@property (nonatomic, assign) BOOL isTestSuccess;
@property (nonatomic, assign) BOOL isStartTimer;
@property (nonatomic, assign) BOOL isOpenGiftProps;
@property (nonatomic, assign) BOOL isOpenHallProps;
@property (nonatomic, assign) BOOL isOpenDiscountProps;
@property (nonatomic, assign) BOOL isOpenThreeInOneEntrance;
@property (nonatomic, assign) BOOL isRoleReport;
@property (nonatomic, assign) BOOL isPayData;
@property (nonatomic, assign) BOOL isLogin;
@property (nonatomic, assign) NSInteger initCode;
@property (nonatomic, copy) NSString *extend_status;

@property (nonatomic, strong) QPJHFunRoleModel *roleModel;
@property (nonatomic, strong) QPJFunPayModel *payModel;
@property (nonatomic, strong) SQPJHTool *tool;

@property (nonatomic, strong) UIView *coverView;
 
@property (nonatomic, strong) UIWindow *keyWindow;

@property (nonatomic) Reachability *reachability;

@end

@implementation JHLCoreEntity
+ (JHLCoreEntity *)sharedInstance {
    static JHLCoreEntity *sharedManagerInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManagerInstance = [[self alloc] init];
        
    });
    return sharedManagerInstance;
}

- (SQPJHTool *)tool {
    if (_tool == nil) {
        _tool = [SQPJHTool new];
    }
    return _tool;
}
- (SQPDetectParam *)detect {
    if (_detect == nil) {
        _detect = [SQPDetectParam new];
    }
    return _detect;
}

#pragma mark - JHLCoreEntity方法
/**
 设置监听
 */
- (void)qpjh_setStartLoginListener:(id)loginListener {
    [JHLCoreEntity sharedInstance].delegate = loginListener;
    [[libQPJHLightChannel sharedInstance] qpjhChannel_setStartLoginListener:self];
}

/**
 显示苹果登录按钮，必须先设置监听
*/
- (void)qpjh_lightLoginStart {
    if ([[QPJHFunDataFormat QPJHGetGameID] length] == 0) {
        [[[QPSaccountStore sharedInstance] getCurrentWindow] makeToast:@"请在QPJHPLIST.h中设置game_id"];
        return;
    }
    if (self.isLogin == NO) {
        self.isLogin = YES;
                
        if (self.initCode == 200) {
            [self platformLogin];
        } else if (self.initCode == 204) {
            [self platformLogin];
        } else {
            [self initSDKByLogin:YES];
        }

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.isLogin = NO;
        });
    }
}

- (void)platformLogin {
    dispatch_async(dispatch_get_main_queue(), ^{
        [[libQPJHLightChannel sharedInstance] qpjhChannel_lightLoginStart];
    });
}

/**
 提交角色信息(在 创建角色、 进入游戏、 升级角色 时都要调用该方法.)
 @param roleData json 数据(请按要求传入 json 格式的 NSString 类型)
  */
- (void)qpjh_superRoleUpdate:(NSString *)roleData {

    if (self.isRoleReport == NO) {
        self.isRoleReport = YES;

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.isRoleReport = NO;
        });
        
        QPJHFunRoleModel *roleModel = [QPJHFunRoleModel yy_modelWithJSON:roleData];
        roleModel.super_user_id = self.super_user_id;
        roleModel.game_id = [QPJHFunDataFormat QPJHGetGameID];
        roleModel.platform_id = self.platform_id;
        if ([self.detect qp_detectContainsEmptyString:roleModel]) {
            return;
        }
        roleModel = [self.detect qp_handleRoleParam:roleModel];

        NSString *random = [QPJHFunDataFormat QPJHMD5GetRandomStr];
        NSString *md5str = [NSString stringWithFormat:@"%@%@%@%@%@",roleModel.super_user_id,roleModel.game_id,roleModel.service_id,random,QPJHKey];
        NSString *sign = [QPJHFunDataFormat QPJHMD5WithNSString:md5str];

        NSDictionary *params = @{@"super_user_id":roleModel.super_user_id,
                                 @"game_id":roleModel.game_id,
                                 @"service_id":roleModel.service_id,
                                 @"service_name":roleModel.service_name,
                                 @"role_id":roleModel.role_id,
                                 @"role_name":roleModel.role_name,
                                 @"role_level":roleModel.role_level,
                                 @"power_value":roleModel.power_value,
                                 @"describe":roleModel.describe,
                                 @"money":roleModel.money,
                                 @"experience":roleModel.experience,
                                 @"role_type":roleModel.role_type,
                                 @"random":random,
                                 @"sign":sign,
                                 @"os_type":@"2",
                                };

        __weak typeof(self) weakSelf = self;
        [SQPJHNetworkManager PostWithURL:@"https://supersdk.7pa.com/role/index" Params:params success:^(id responseObject) {
            __strong __typeof(weakSelf) strongSelf = weakSelf;
            NSDictionary *surperdic = (NSDictionary *)responseObject;
            strongSelf.rolesurperdic = surperdic;
            NSString *surpercode = [NSString stringWithFormat:@"%@",surperdic[@"code"]];

            if ([surpercode isEqualToString:@"200"]) {
                NSString *superRole_id = [NSString stringWithFormat:@"%@",surperdic[@"data"][@"role_id"]];
                roleModel.super_role_id = superRole_id;
                strongSelf.roleModel = roleModel;
                strongSelf.roleLevel = roleModel.role_level;
                
                NSLog(@"superRole_id == %@", superRole_id);
                //这里需要去掉无效角色
                if ([QPJHFunDataFormat isBlankString:superRole_id]) {
                    return;
                }
                
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        QPJHChannelRoleInfo *info = [[QPJHChannelRoleInfo alloc] init];
                        info.role_type = roleModel.role_type;
                        info.service_id = roleModel.service_id;
                        info.service_name = roleModel.service_name;
                        info.role_id = superRole_id;
                        info.role_name = roleModel.role_name;
                        info.role_level = roleModel.role_level;
                        info.power_value = roleModel.power_value;
                        info.params = params;
                        info.responseObject = strongSelf.loginResponse;
                        [[libQPJHLightChannel sharedInstance] qpjhChannel_superRoleUpdate:info];

                    });
                });
                    
            }
            
        } failure:^(NSString *error) {
            
        }];

    }
}

/**
 创建订单接口
 @param orderData json 数据(请按要求传入 json 格式的 NSString 类型)
 */
- (void)qpjh_superOrder:(NSString *)orderData {
    QPJFunPayModel *payModel = [QPJFunPayModel yy_modelWithJSON:orderData];
    payModel.super_user_id = self.super_user_id;
    payModel.super_role_id = self.roleModel.super_role_id;
    payModel.platform_id = self.roleModel.platform_id;
    payModel.role_id = self.roleModel.role_id;
    payModel.role_name = self.roleModel.role_name;
    payModel.service_id = self.roleModel.service_id;
    payModel.service_name = self.roleModel.service_name;

    if ([self.detect qp_detectPayContainsEmptyString:payModel]) {
        return;
    }
    payModel = [self.detect qp_handlePayParam:payModel RoleInfo:self.roleModel];
    
    if ([self.platform_id isEqualToString:@"1"] && self.isTestSuccess == NO) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self testLogic:orderData];
        });
        return;
    }
    
    if (self.isPayData == NO) {
        self.isPayData = YES;
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.isPayData = NO;
        });
        
        self.isTestSuccess = NO;

        NSString *package = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
        NSString *random = [QPJHFunDataFormat QPJHMD5GetRandomStr];
        NSString *md5str = [NSString stringWithFormat:@"%@%@%@%@%@%@",payModel.super_user_id,payModel.platform_id,payModel.game_order_sn,self
                            .roleModel.game_id,random,QPJHKey];
        NSString *sign = [QPJHFunDataFormat QPJHMD5WithNSString:md5str];
        
        NSDictionary *params = @{@"good_id":payModel.good_id,
                                 @"good_name":payModel.good_name,
                                 @"platform_id":self.roleModel.platform_id,
                                 @"game_id":self.roleModel.game_id,
                                 @"game_order_sn":payModel.game_order_sn,
                                 @"package":package,
                                 @"super_user_id":self.super_user_id,
                                 @"power_value":self.roleModel.power_value,
                                 @"money":payModel.money,
                                 @"service_id":self.roleModel.service_id,
                                 @"service_name":self.roleModel.service_name,
                                 @"role_id":self.roleModel.role_id,
                                 @"role_name":self.roleModel.role_name,
                                 @"remark":payModel.remark,
                                 @"os_type":@"2",
                                 @"random":random,
                                 @"sign":sign,
                                };

        NSString *orderUrl =  [libQPJHLightChannel sharedInstance].orderUrl;
        [SQPJHNetworkManager PostWithURL:orderUrl Params:params success:^(id responseObject) {
            NSDictionary *surperdic = (NSDictionary *)responseObject;
            NSString *surpercode = [NSString stringWithFormat:@"%@",surperdic[@"code"]];
            NSString *msg = [NSString stringWithFormat:@"%@",surperdic[@"msg"]];
            NSString *order_id = [NSString stringWithFormat:@"%@",surperdic[@"data"][@"order_id"]];
            NSString *extend_status = [NSString stringWithFormat:@"%@",surperdic[@"data"][@"extend_status"]];
            
            payModel.superOrderID = order_id;
            self.payModel = payModel;
            NSDictionary *dicSusParam = @{@"order_id":@"",@"cpOrder":@""};
            if (self.payModel) {
                dicSusParam = @{@"order_id":self.payModel.superOrderID,@"cpOrder":self.payModel.game_order_sn};
            }
            
            if ([surpercode isEqualToString:@"200"]) {
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if ([extend_status isEqualToString:@"1"]) {
                            QPJHPayView *popView = [QPJHPayView new];
                            [popView binGoodname:payModel.good_name Money:payModel.money Orderid:order_id];
                            popView.payBlock = ^(NSString * _Nonnull paytype) {
                                if ([paytype isEqualToString:@"1"]) {
                                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                                        dispatch_async(dispatch_get_main_queue(), ^{
                                            if ([self.delegate respondsToSelector:@selector(applePayCallBack:data:)]) {
                                                [self.delegate getPaySuccessCallBack:dicSusParam];
                                            }
                                        });
                                    });
                                } else {
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                                            dispatch_async(dispatch_get_main_queue(), ^{
                                                if ([self.delegate respondsToSelector:@selector(applePayCallBack:data:)]) {
                                                    [self.delegate getPayFailCallBack:dicSusParam];
                                                }
                                            });
                                        });
                                    });
                                }
                            };
                            [popView show];
                        } else {
                            QPJHChannelOrderInfo *info = [[QPJHChannelOrderInfo alloc] init];
                            info.goodID = payModel.good_id;
                            info.payMoney = payModel.money;
                            info.goodName = payModel.good_name;
                            info.gameOrderSn = order_id;
                            info.serviceId = payModel.service_id;
                            info.serviceName = payModel.service_name;
                            info.roleId = self.roleModel.super_role_id;
                            info.roleName = payModel.role_name;
                            info.powerValue = self.roleModel.power_value;
                            info.remark = payModel.remark;
                            info.params = params;
                            info.responseObject = responseObject;
                            [[libQPJHLightChannel sharedInstance] qpjhChannel_superOrder:info];
                        }
                    });
                });
                
            } else {
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[[QPSaccountStore sharedInstance] getCurrentWindow] makeToast:msg];
                        if ([self.delegate respondsToSelector:@selector(getPayFailCallBack:)]) {
                            [self.delegate getPayFailCallBack:dicSusParam];
                        }
                    });
                });

            }
            
        } failure:^(NSString *error) {
            
        }];

    }
}

/**
 退出登录接口
 */
- (void)qpjh_logout {
    NSLog(@"qipa logout");
    self.isTestSuccess= NO;
    self.isStartTimer = NO;
    self.super_user_id = nil;
    self.roleModel = nil;
    self.payModel = nil;
    self.roleLevel = nil;
    [[libQPJHLightChannel sharedInstance] qpjhChannel_logout];
    
}

#pragma mark - 跳转小程序
- (void)qpjh_jump_miniPrograms {
    NSLog(@"qipa qpjh_jump_miniPrograms");
    [[libQPJHLightChannel sharedInstance] qpjhChannel_jump_miniPrograms];
}

/**
 账号删除
 */
- (void)qpjh_logoutForAccountDelete {
    NSLog(@"qipa qpjh_logoutForAccountDelete");
    self.isTestSuccess= NO;
    self.isStartTimer = NO;
    self.super_user_id = nil;
    self.roleModel = nil;
    self.payModel = nil;
    self.roleLevel = nil;
    [[libQPJHLightChannel sharedInstance] qpjhChannel_logoutForAccountDelete];
}

/**
 选择区服【停止新增用户】(接口说明: 玩家在选择区服时调用. )
 @param service_id   当前选择的服务器ID
 @param service_name 当前选择的服务器名
 */
- (void)qpjh_canEnterGameWithServiceID:(NSString *)service_id ServiceName:(NSString *)service_name {
    if ([QPJHFunDataFormat isBlankString:service_id]) {
        [[[QPSaccountStore sharedInstance] getCurrentWindow] makeToast:@"区服ID为空"];
        return;
    }
    if ([QPJHFunDataFormat isBlankString:service_name]) {
        [[[QPSaccountStore sharedInstance] getCurrentWindow] makeToast:@"区服名为空"];
        return;
    }
    if ([QPJHFunDataFormat isBlankString:self.super_user_id]) {
        [[[QPSaccountStore sharedInstance] getCurrentWindow] makeToast:@"未检测到您的登录信息"];
        return;
    }
    
    [self.tool qpjh_canEnterGameWithServiceID:service_id ServiceName:service_name User_id:self.super_user_id SuccessBlock:^(id  _Nonnull result) {
        NSString *resultstr = [NSString stringWithFormat:@"%@",result];
        if ([self.delegate respondsToSelector:@selector(canEnterListenCallBack:)]) {
            [self.delegate canEnterListenCallBack:resultstr];
        }
    } FailureBlock:^(id  _Nonnull result) {
        if ([self.delegate respondsToSelector:@selector(canEnterListenCallBack:)]) {
            [self.delegate canEnterListenCallBack:@"0"];
        }
    }];
}



/**
 登录回调接口
 @param game_id 聚合游戏ID
 @param token 渠道返回
 @param platform_id 平台ID 后台渠道列表ID  母包测试等于1
 @param uid 渠道返回唯一标识
 @param channel_code 渠道返回 扩展标识  选传
 @response super_user_id 进入游戏唯一标识
 @response token 游戏服务器效验参数
 */
#pragma mark - 登录回调接口
- (void)qpjh_superLoginCallBackWithGame_id:(NSString *)game_id token:(NSString *)token platform_id:(NSString *)platform_id uid:(NSString *)uid channel_code:(NSString *)channel_code url:(NSString *)url {
    
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                            game_id,@"game_id",
                            token,@"token",
                            platform_id,@"platform_id",
                            uid,@"uid",
                            channel_code,@"channel_code",
                            @"2",@"os_type",
                            nil];
        
    [SQPJHNetworkManager PostWithURL:url Params:params success:^(id responseObject) {
       
        NSDictionary *loginResponse = (NSDictionary *)responseObject;
        self.loginResponse = loginResponse;
        NSDictionary *surperdic = (NSDictionary *)responseObject[@"data"];
                
        NSString *code = [NSString stringWithFormat:@"%@", responseObject[@"code"]];
        NSString *msg = [NSString stringWithFormat:@"%@", responseObject[@"msg"]];
        
        if ([code isEqualToString:SuccessCode]) {
            NSString *surper_user_id = [NSString stringWithFormat:@"%@",surperdic[@"super_user_id"]];
            self.super_user_id = surper_user_id;
            
            NSString *token = [NSString stringWithFormat:@"%@",surperdic[@"token"]];
            
            if (token.length > 5) {
                NSString *timeStamp = [self ddpGetExpectTimestamp:-19 month:-2 day:-1];
                
                NSString *dateStr = [self getTimeFromTimestamp:timeStamp];
                
                NSDictionary *dic1 = @{
                                       @"channel_id":self.platform_id,
                                       @"super_user_id":surper_user_id,
                                       @"token":token,
                                       @"auth":@"1",
                                       @"birthday":dateStr,
                                       };
                
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            if ([self.delegate respondsToSelector:@selector(qpjh_LightGetChannelLoginCallBack:)]) {
                                [self.delegate qpjh_LightGetChannelLoginCallBack:dic1];
                            }
                        });
                });
            }
        } else {
            
        }
        
    } failure:^(NSString *error) {
        
    }];
}



- (void)testLogic:(NSString *)orderData {
    UIWindow *keyWindow = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.keyWindow = keyWindow;
    self.keyWindow.backgroundColor = [UIColor whiteColor];
    self.keyWindow.rootViewController = [[UIViewController alloc] init];
    self.keyWindow.windowLevel = UIWindowLevelStatusBar + 1;
    [self.keyWindow makeKeyAndVisible];
    
    QPJFunPayModel *payModel = [QPJFunPayModel yy_modelWithJSON:orderData];
    NSDictionary *dicSusParam = @{@"order_id":@"",@"cpOrder":payModel.game_order_sn};

    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"选择客户端支付回调" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *successAction = [UIAlertAction actionWithTitle:@"支付成功" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.isTestSuccess = YES;
        [self qpjh_superOrder:orderData];
        
        [self.keyWindow.rootViewController removeFromParentViewController];
        
        self.keyWindow.rootViewController = nil;
        self.keyWindow.hidden = YES;
        [self.keyWindow resignKeyWindow];
        self.keyWindow = nil;
    }];
    UIAlertAction *failAction = [UIAlertAction actionWithTitle:@"支付失败" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    if ([self.delegate respondsToSelector:@selector(getPayFailCallBack:)]) {
                        [self.delegate getPayFailCallBack:dicSusParam];
                    }
                });
            });
        });
        [self.keyWindow.rootViewController removeFromParentViewController];
        self.keyWindow.rootViewController = nil;
        self.keyWindow.hidden = YES;
        [self.keyWindow resignKeyWindow];
        self.keyWindow = nil;
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"支付取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        dispatch_async(dispatch_get_main_queue(), ^{
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    if ([self.delegate respondsToSelector:@selector(getPayCancelCallBack:)]) {
                        [self.delegate getPayCancelCallBack:dicSusParam];
                    }
                });
            });
        });
        [self.keyWindow.rootViewController removeFromParentViewController];
        self.keyWindow.rootViewController = nil;
        self.keyWindow.hidden = YES;
        [self.keyWindow resignKeyWindow];
        self.keyWindow = nil;
    }];
    [alertController addAction:successAction];
    [alertController addAction:failAction];
    [alertController addAction:cancelAction];
    [keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
}

// 获取当前时间的: 前一周(day:-7)丶前一个月(month:-30)丶前一年(year:-1)的时间戳
- (NSString *)ddpGetExpectTimestamp:(NSInteger)year month:(NSUInteger)month day:(NSUInteger)day {
    
    NSDate *currentdata = [NSDate date];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    
    NSDateComponents *datecomps = [[NSDateComponents alloc] init];
    [datecomps setYear:year?:0];
    [datecomps setMonth:month?:0];
    [datecomps setDay:day?:0];
    
    NSDate *calculatedate = [calendar dateByAddingComponents:datecomps toDate:currentdata options:0];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    NSString *result = [NSString stringWithFormat:@"%ld", (long)[calculatedate timeIntervalSince1970]];
    
    return result;
}

#pragma mark ---- 将时间戳转换成时间
- (NSString *)getTimeFromTimestamp:(NSString *)tamp{
    
    NSDate * myDate=[NSDate dateWithTimeIntervalSince1970:[tamp doubleValue]];
    
    NSDateFormatter * formatter=[[NSDateFormatter alloc] init];
    
    [formatter setDateFormat:@"YYYY-MM-dd"];
    
    NSString *timeStr=[formatter stringFromDate:myDate];
    
    return timeStr;
    
}


#pragma mark - QPJHLightChannelDelegate
/**
 登录回调
 loginResult 0取消 1成功 2失败
 成功时data为
 @{
 @"super_user_id": self.userId,
 @"token": accessToken
};
 */
- (void)qpjhChannel_LightGetChannelLoginCallBack:(NSDictionary *)result {
    NSString *token = result[@"token"];
    NSString *uid = result[@"uid"];
    NSString *channel_code = result[@"channel_code"];
    if ([QPJHFunDataFormat isBlankString:channel_code]) {
        channel_code = @"";
    }

    NSString *loginUrl =  [libQPJHLightChannel sharedInstance].loginUrl;

    [self qpjh_superLoginCallBackWithGame_id:[QPJHFunDataFormat QPJHGetGameID] token:token platform_id:self.platform_id uid:uid channel_code:channel_code url:loginUrl];
}

//聚合渠道:上报角色回调
- (void)qpjhChannel_getUpdateRoleCallBack:(NSDictionary *)result {

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([self.delegate respondsToSelector:@selector(getUpdateRoleCallBack:)]) {
                [self.delegate getUpdateRoleCallBack:result];
            }
        });
    });
    
    [[QPJHTool sharedInstance] bootIndexWithRoleInfo:self.roleModel isStartTimer:self.isStartTimer isReport:YES];
    if (self.isStartTimer == NO) {
        self.isStartTimer = YES;
    }
}

//聚合渠道:支付成功回调
- (void)qpjhChannel_getPaySuccessCallBack:(NSDictionary *)result {
    NSDictionary *dicSusParam = @{@"order_id":@"",@"cpOrder":@""};
    if (self.payModel) {
        dicSusParam = @{@"order_id":self.payModel.superOrderID,@"cpOrder":self.payModel.game_order_sn};
    }
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([self.delegate respondsToSelector:@selector(getPaySuccessCallBack:)]) {
                [self.delegate getPaySuccessCallBack:dicSusParam];
            }
        });
    });
}

//聚合渠道:支付失败回调
- (void)qpjhChannel_getPayFailCallBack:(NSDictionary *)result {
    NSDictionary *dicSusParam = @{@"order_id":@"",@"cpOrder":@""};
    if (self.payModel) {
        dicSusParam = @{@"order_id":self.payModel.superOrderID,@"cpOrder":self.payModel.game_order_sn};
    }

    dispatch_async(dispatch_get_main_queue(), ^{
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([self.delegate respondsToSelector:@selector(getPayFailCallBack:)]) {
                    [self.delegate getPayFailCallBack:dicSusParam];
                }
            });
        });
    });
}

//聚合渠道:支付取消回调
- (void)qpjhChannel_getPayCancelCallBack:(NSDictionary *)result {
    NSDictionary *dicSusParam = @{@"order_id":@"",@"cpOrder":@""};
    if (self.payModel) {
        dicSusParam = @{@"order_id":self.payModel.superOrderID,@"cpOrder":self.payModel.game_order_sn};
    }

    dispatch_async(dispatch_get_main_queue(), ^{
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([self.delegate respondsToSelector:@selector(getPayCancelCallBack:)]) {
                    [self.delegate getPayCancelCallBack:dicSusParam];
                }
            });
        });
    });
}

//聚合渠道:注销, 切换账号回调
- (void)qpjhChannel_logOutCallBack:(NSString *)result {
    self.isStartTimer = NO;
    self.super_user_id = nil;
    self.roleModel = nil;
    self.payModel = nil;
    self.roleLevel = nil;
    if ([self.delegate respondsToSelector:@selector(logOutCallBack:)]) {
        [self.delegate logOutCallBack:@"success"];
    }
        
    NSLog(@"qipa logOutCallBack");
}

#pragma mark - UIApplicationDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    NSString *platform_id =  [libQPJHLightChannel sharedInstance].platformId;
    self.platform_id = platform_id;
    
    [self initBaseDatas];
    
    [self listenNetwork];
    
    [self initSDKByLogin:NO];
      
    [[libQPJHLightChannel sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    
    return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
    [[libQPJHLightChannel sharedInstance] applicationWillResignActive:application];
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[libQPJHLightChannel sharedInstance] applicationDidEnterBackground:application];
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
    [[libQPJHLightChannel sharedInstance] applicationWillEnterForeground:application];
}
- (void)applicationDidBecomeActive:(UIApplication*)application
{
    [[libQPJHLightChannel sharedInstance] applicationDidBecomeActive:application];
}
- (void)applicationWillTerminate:(UIApplication *)application {
    [[libQPJHLightChannel sharedInstance] applicationWillTerminate:application];
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [[libQPJHLightChannel sharedInstance] application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    [[libQPJHLightChannel sharedInstance] application:application didFailToRegisterForRemoteNotificationsWithError:error];
}
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    return [[libQPJHLightChannel sharedInstance] application:application supportedInterfaceOrientationsForWindow:window];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo {
    [[libQPJHLightChannel sharedInstance] application:application didReceiveRemoteNotification:userInfo];
}
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    return [[libQPJHLightChannel sharedInstance] application:app openURL:url options:options];
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return [[libQPJHLightChannel sharedInstance] application:application handleOpenURL:url];
}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [[libQPJHLightChannel sharedInstance] application:application openURL:url sourceApplication:sourceApplication annotation:annotation];
}
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void(^)(NSArray * restorableObjects))restorationHandler {
    return [[libQPJHLightChannel sharedInstance] application:application continueUserActivity:userActivity restorationHandler:restorationHandler];
}


#pragma mark - 初始化数值
- (void)initBaseDatas {
    self.isStartTimer = NO;
    self.isOpenGiftProps = NO;
    self.isOpenHallProps = NO;
    self.isOpenDiscountProps = NO;
    self.isOpenThreeInOneEntrance = NO;
    self.isRoleReport = NO;
    self.isPayData = NO;
    self.isLogin = NO;

}
- (void)initSDKByLogin:(BOOL)islogin {
    //公告
    [self qpSetNoticeResquestByLogin:islogin block:^(BOOL isFailure) {
        if (isFailure) {//这里首次请求可能还没有网络权限，需要递归直至有网络为止，其他接口也须在此完成之后
            [self initSDKByLogin:islogin];
        }
    }];
    
}

- (void)qpSetNoticeResquestByLogin:(BOOL)islogin block:(void(^)(BOOL isFailure))block {
    
    [self.tool qpSetNoticeViewWithPlatform_ID:self.platform_id SuccessBlock:^(id  _Nonnull result) {
        NSDictionary *surperdic = (NSDictionary *)result;
        NSString *surpercode = [NSString stringWithFormat:@"%@",surperdic[@"code"]];
        if ([surpercode isEqualToString:@"200"]) {
            self.initCode = [surpercode integerValue];
            NSString *extend_status = [NSString stringWithFormat:@"%@",surperdic[@"data"][@"extend_status"]];
            
            if ([extend_status isEqualToString:@"1"]) {
                self.extend_status = extend_status;
                block(NO);
            } else {
                if (islogin == NO) {
                    NSArray *notice_data = surperdic[@"data"][@"notice_data"];
                    if (notice_data.count != 0) {
                        NSString *notice_title = [NSString stringWithFormat:@"%@",surperdic[@"data"][@"notice_data"][@"notice_title"]];
                        if (([notice_title isKindOfClass:[NSNull class]]||notice_title == nil||[[NSString stringWithFormat:@"%@",notice_title] length] < 1||[[NSString stringWithFormat:@"%@",notice_title] isEqualToString:@"(null)"])) {
                            block(NO);
                        } else {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                QPJHInitNoticeView *popView = [[QPJHInitNoticeView alloc] init];
                                [popView binData:surperdic];
                                [popView show];
                                popView.closeBlock = ^{
                                    block(NO);
                                };
                            });
                        }
                    } else {
                        block(NO);
                    }
                } else {
                    block(NO);
                }
            }
        } else {
            block(NO);
        }
    } FailureBlock:^(id  _Nonnull result) {
        block(YES);
    }];
}

- (void)listenNetwork {

    //注册网络状态通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(networkStatusChanged:) name:kReachabilityChangedNotification object:nil];
    //获取Reachability对象
    self.reachability = [Reachability reachabilityForInternetConnection];
    //开始监听网络变化
    [self.reachability startNotifier];
    // 立即进行一次初始的网络状态检测
    QPNetworkStatus networkStatus = [self.reachability currentReachabilityStatus];
    [self networkStatusChangedWithNetworkStatus:networkStatus];

}

- (void)networkStatusChanged:(NSNotification*)notification {

    Reachability*reachability = (Reachability*)notification.object;
    QPNetworkStatus networkStatus = [reachability currentReachabilityStatus];
    [self networkStatusChangedWithNetworkStatus:networkStatus];

}

- (void)networkStatusChangedWithNetworkStatus:(QPNetworkStatus)networkStatus {

    // 判断是否有网络连接
    if(networkStatus ==NotQPReachable) {
        NSLog(@"qpbt - 无网络连接");
        
    } else {
        //这里调用自己加载数据的方法
        NSLog(@"qpbt - 有网络连接");
        
        //渠道初始化网络的操作
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //初始化游戏部分，游戏初始化设置需要网络可放在这里面
                if ([self.delegate respondsToSelector:@selector(qpjh_LightAfterNerwork_init)]) {
                    [self.delegate qpjh_LightAfterNerwork_init];
                }
                
                //初始化yzysdk部分，yzysdk初始化设置需要网络可放在这里面
                [[libQPJHLightChannel sharedInstance] qpjhAfterNerwork_init];

            });
        });
    }

}

- (void)dealloc {

    [self removeNetworkListener];

}

- (void)removeNetworkListener {

    [self.reachability stopNotifier];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
    self.reachability = nil;

}


@end
